﻿using System;
using System.Drawing.Imaging;
using System.Drawing;
using System.IO;

namespace SplitCode
{
    public class JpegCoder : ICoder
    {
        private EncoderParameters _encoderParameters;
        private ImageCodecInfo _imageCodecInfo;
        private Image _image;
        private FrameDimension _dim;
        private string _inputImageName;
        private ConfObj _config;

        #region ICoder Members

        public void Prepare(ConfObj config)
        {
            _config = config;
            decimal quality = config.quality;
            if (quality > 10 || quality < 0)
                throw new ArgumentOutOfRangeException("Quality is out of valid range");

            _encoderParameters = new EncoderParameters(1);
            _encoderParameters.Param[0] = new EncoderParameter(Encoder.Quality, (long)(quality * 10));
            _imageCodecInfo = GetEncoder(ImageFormat.Jpeg);
        }

        public int LoadImage(string fileName)
        {
            _inputImageName = fileName;
            _image = Image.FromFile(fileName);
            Guid guid = _image.FrameDimensionsList[0];
            _dim = new FrameDimension(guid);
            return _image.GetFrameCount(_dim);
        }

        public void Save(int pageNum)
        {
            _image.SelectActiveFrame(_dim, pageNum);
            string outputFileName = null;

            if (String.IsNullOrEmpty(_config.outDir))
            {
                outputFileName = Path.Combine(Path.GetDirectoryName(_inputImageName), String.Format("{0}_{1}.jpg",
                    Path.GetFileNameWithoutExtension(_inputImageName), pageNum + 1));
            }
            else
            {
                outputFileName = Path.Combine(_config.outDir, String.Format("{0}_{1}.jpg",
                    Path.GetFileNameWithoutExtension(_inputImageName), pageNum + 1));
            }

            if (!_config.doOverwrite)
            {
                outputFileName = HelperMethods.ModifyFileName(outputFileName);
            }

            _image.Save(outputFileName, _imageCodecInfo, _encoderParameters);
        }

        public void Close()
        {
            _image.Dispose();
        }

        #endregion

        private static ImageCodecInfo GetEncoder(ImageFormat format)
        {
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();

            foreach (ImageCodecInfo codec in codecs)
            {
                if (codec.FormatID == format.Guid)
                {
                    return codec;
                }
            }
            return null;
        }

    }
}
